﻿var fileUploadUrl = "/_layouts/Sukul.SharePoint.Taxomatic/TaxomaticHandler.ashx?mode=import";
var fileConvertUrl = "/_layouts/Sukul.SharePoint.Taxomatic/TaxomaticHandler.ashx?mode=convert";
var interval;
///
/// Calls a web service using JSON
///
function CallWebService(url, input, callBack) {
    var request = null;
    if (input != null) {
        request = { "Args": input };
        request = "request=" + JSON.stringify(request);
    }
    //$.getJSON(url, request, callBack);
    $.ajax({
        type: "GET",
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: request,
        processdata: true,
        success: callBack
    });
}

function Version_Entry_Load() {
    CallWebService("/_vti_bin/Sukul.SharePoint.Taxomatic/TaxomaticService.svc/GetVersion", null, onSuccessGetVersion);
}

function Entry_Load() {
    ShowProgress();

    $("#myTestMenu").splitbutton({ plain: true, menu: '#myMenu' });
    $("#btnVersion").button();
    $("#btnImport").button();
    $("#btnExport").button();
    $("#btnConvert").button();
    $("#btnSync").button().click(function () {
        if (confirm("Do you want to proceed with syncing the hidden terms list?") == true) {
            CallWebService("/_vti_bin/Sukul.SharePoint.Taxomatic/TaxomaticService.svc/SyncHiddenList", "", onSuccessSync);
        }
    });
    CallWebService("/_vti_bin/Sukul.SharePoint.Taxomatic/TaxomaticService.svc/GetTerms", "", onSuccessGetTerms);
    Bannerize();
    //CallWebService(null, "GetTerms");

}

function Import_Load() {
    $("#msg").text("");
    /* Upload control */
    var uploader = new qq.FileUploader({
        // pass the dom node (ex. $(selector)[0] for jQuery users)
        element: $('#txtImport')[0],
        // path to server-side upload script
        action: fileUploadUrl,
        allowedExtensions: ['xml'],
        debug: false,
        onProgress: function (id, fileName, loaded, total) {
            $("#msg").html("Processsing " + loaded + " out of " + total);
        },
        onSubmit: function (id, fileName) {
            /* Only one upload at a time */
            $("#msg").html("");
        },
        onCancel: function (id, fileName) { this.enable(); },
        onComplete: function (id, fileName, response) {
            if (response.IsSuccess == false) {
                $("#msg").html("");
                $("#vw_Error").html("").tmpl(response).appendTo("#msg");
                $("#Messages").tabs();
                //$("#msg").html("ERROR <br/>" + response.Payload.ErrorLog);
            }
            else {
                $("#msg").html("Processed successfully");
                // window.frameElement.commitPopup();
                // window.frameElement.commonModalDialogClose(1, 1);
            }

        }
    });
}

/* Converts the supplied div tag into a banner */
function Bannerize() {
    //$(".prev").button();
    // $(".next").button();
    $("#banner").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev",
        auto: 2000,
        speed: 8000,
        visible: 1
    });
};

function ShowProgress() {
    $("#Progress").show();
}

function HideProgress() {
    $("#Progress").hide();
}

function onSuccessSync(retVal) {
    retVal = JSON.parse(retVal);
    if (retVal.IsSuccess == true) {
        alert("Sync succeeded");
    }
    else {
        alert("Sync failed");
    }
}

function onSuccessGetVersion(retVal) {
    retVal = JSON.parse(retVal);
    if (retVal.IsSuccess == true) {
        $("#version").html(retVal.Payload.toString());
    }
    else {
        alert(retVal.ErrorMessage);
    }
}

function onSuccessGetTerm(retVal) {
    HideProgress();
    var inEventHandler = false;
    retVal = JSON.parse(retVal);
    if (retVal.IsSuccess == true) {
        $("#divTerm").html("");
        $("#vw_Term").html("").tmpl(retVal.Payload).appendTo("#divTerm");
    }
    else {
        alert(retVal.ErrorMessage);
    }
}

/* Gets called on a successful WCF service call. Renders the output to the user. */
function onSuccessGetTerms(retVal) {
    HideProgress();
    var inEventHandler = false;
    retVal = JSON.parse(retVal);
    if (retVal.IsSuccess == true) {
        $("#vw_Parent").tmpl(retVal).appendTo("#tree");
        $("#tree").dynatree({
            persist: true,
            checkbox: true,
            selectMode: 2,
            onSelect: function (flag, dtnode) {
                // This will happen each time a check box is selected/deselected
                var selectedNodes = dtnode.tree.getSelectedNodes();
                var selectedKeys = $.map(selectedNodes, function (node) {
                    return node.data.key;
                });
                // Set the hidden input field's value to the selected items
                $('#SelectedItems').val(selectedKeys.join(","));

                // Select child nodes
                // Ignore, if this is a recursive call
                if (!inEventHandler) {
                    inEventHandler = true;
                    // Select all children of currently selected node
                    try {
                        inEventHandler = true;
                        dtnode.visit(function (childNode) {
                            childNode.select(flag);
                        });
                    }
                    finally {
                        inEventHandler = false;
                    }
                }
            },
            onClick: function (node) {
                if (!node.data.isFolder) {
                    ShowProgress();
                    CallWebService("/_vti_bin/Sukul.SharePoint.Taxomatic/TaxomaticService.svc/GetSingleTerm", node.data.key.toString(), onSuccessGetTerm); ;
                }
            },
            onKeydown: function (node, event) {
                // Eat keyboard events, when a menu is open        
                if ($(".contextMenu:visible").length > 0) return false; switch (event.which) {
                    // Open context menu on [Space] key (simulate right click)                            
                    case 32: // [Space]         
                        $(node.span).trigger("mousedown", { preventDefault: true, button: 2 })
              .trigger("mouseup", { preventDefault: true, pageX: node.span.offsetLeft, pageY: node.span.offsetTop, button: 2 }); return false;
                        // Handle Ctrl-C, -X and -V       
                    case 67: if (event.ctrlKey) {
                            // Ctrl-C 
                            copyPaste("copy", node); return false;
                        } break; case 86: if (event.ctrlKey) {
                            // Ctrl-V  
                            copyPaste("paste", node); return false;
                        } break; case 88: if (event.ctrlKey) {
                            // Ctrl-X            
                            copyPaste("cut", node); return false;
                        } break;
                }
            }
        });

        // Add context menu handler to tree nodes    
        bindContextMenu();

        //        onClick: function (node, event) {
        //                // Eat mouse events, while a menu is open        
        //                if ($(".contextMenu:visible").length > 0) { return false; }
        //            },
    }
    else {
        alert(retVal.ErrorMessage);
    }
}

/* Gets called on an unexpected error */
function onFail(err) {
    HideProgress();
    alert(err._message);
}

/* Displays the error message to the user */
function ErrorHandler(retVal) {
    // $("#errorDiv").show();
    // $("#resultsDiv").hide();
    // note: chaining does not work for templates
    // $("#errorDialogDetails").html("");
    // $("#errorDiv").html("");
    // $("#vw_Error").tmpl(retVal).appendTo("#errorDialogDetails");
    // $("#vw_Error").tmpl(retVal).appendTo("#errorDiv")
    // $("#errorDialog").dialog({ width: 600 });

    var clipboardNode = null;
    var pasteMode = null;
}

function bindContextMenu() {
    // Add context menu to all nodes:    alert("Adding context menu");
    //    $(".mymenu")
    //			.destroyContextMenu() // unbind first, to prevent duplicates
    //			.contextMenu({ menu: "myMenu" }, function (action, el, pos) {
    //			    // The event was bound to the <span> tag, but the node object
    //			    // is stored in the parent <li> tag
    //			    var node = el.parent().attr("dtnode");
    //			    switch (action) {
    //			        case "cut":
    //			        case "copy":
    //			        case "paste":
    //			            copyPaste(action, node);
    //			            break;
    //			        default:
    //			            alert("Todo: appply action '" + action + "' to node " + node);
    //			    }
    //			});
}
